import 'package:cave_flutter/utils/whl_record_voice_utils.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class WhlRecordSheetLogic extends GetxController {
  bool isRecording = false;
  int recordIngTime = 0;
  int maxRecordTime = 60;
  bool isMoveOut = false;
  WhlRecordVoiceUtils recordVoiceUtils = WhlRecordVoiceUtils();
  RecordVoiceModel? recordVoiceModel;
  String timeText = '00:00';

  @override
  void onClose() {
    super.onClose();
    recordVoiceUtils.stopRecord();
  }

  @override
  void onInit() {
    super.onInit();
    recordVoiceUtils.initRecord();
  }

  void startRecording() async {
    isRecording = true;
    recordIngTime = 0;
    update();
    recordVoiceUtils.start((time) {
      if (recordIngTime != time) {
        recordIngTime = time;
        var date = DateTime.fromMillisecondsSinceEpoch(recordIngTime * 1000, isUtc: true);
        var txt = DateFormat('mm:ss').format(date);
        timeText = txt.substring(0, 5);
        if (recordIngTime > 45) {
          if (recordIngTime >= maxRecordTime) {
            stopRecording();
          }
          update();
        }
        update();
      }
    });
  }

  void stopRecording() async {
    isRecording = false;
    update();
    isMoveOut = false;
    recordVoiceUtils.stopRecord(onSuccess: (RecordVoiceModel model) {
      if (model.status != -1) {
        recordVoiceModel = model;
        Get.back(result: recordVoiceModel);
      }
    });
  }

  doClickSend() async {
    if (isRecording) {
      return;
    }
    if (recordVoiceModel == null) {
      MyToast.show('Please record voice first');
      return;
    }
    Get.back(result: recordVoiceModel);
  }
}
